package org.example;


import cn.hserver.core.ioc.annotation.Bean;
import cn.hserver.core.server.util.protocol.ProtocolUtil;
import cn.hserver.plugin.cloud.ServerInstance;
import cn.hserver.plugin.gateway.bean.Http4Data;
import cn.hserver.plugin.gateway.business.BusinessHttp4;
import cn.hserver.plugin.gateway.business.BusinessHttp7;
import cn.hserver.plugin.rpc.core.RpcDisHandler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
import java.util.concurrent.atomic.LongAdder;

@Bean
public class Http4 extends BusinessHttp4 {
    private static final LongAdder online = new LongAdder();
    AttributeKey<String> ONLINE_KEY = AttributeKey.valueOf("online");

    @Override
    public SocketAddress getProxyHost(ChannelHandlerContext ctx, Http4Data http4Data, SocketAddress sourceSocketAddress) {
        //获取所有，可以自己更具负载进行选择一个
        List<ServerInstance> all = RpcDisHandler.getRpcDisHandler().getDynamicRoundRobin("WEB", "web").getAll();
        System.out.println("注册服务数:" + all.size());
        //在线数统计
        online.increment();
        //通道绑定数据
        ctx.channel().attr(ONLINE_KEY).set(ctx.channel().remoteAddress().toString());



        System.out.println("=============上面只是演示打印==============");
        //轮训策略选择一个
        final var chose = RpcDisHandler.getRpcDisHandler().chose("WEB", "web");
        return new InetSocketAddress(chose.getIp(), chose.getPort());
    }

    @Override
    public Object in(ChannelHandlerContext ctx, Http4Data http4Data) {
        ProtocolUtil.print(ctx.channel(),"入网数据包", (ByteBuf) http4Data.getData());
        return super.in(ctx, http4Data);
    }


    @Override
    public Object out(Channel channel, Object o) {
        ProtocolUtil.print(channel,"出网数据包", (ByteBuf)o);
        return super.out(channel, o);
    }

    @Override
    public void close(Channel channel) {
        if (channel.hasAttr(ONLINE_KEY)) {
            online.decrement();
            Attribute<String> attr = channel.attr(ONLINE_KEY);
            System.out.println("当前关闭的地址：" + attr.get());
        }
        System.out.println("关闭后的当前在线数：" + online);
        super.close(channel);
    }
}
